﻿using System.Text;
using System.Text.RegularExpressions;
using System.Web.Routing;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

namespace System.Web.Mvc
{
    public static class MvcUrlHelper
    {
        #region 设定URL中的键值
        /// <summary>
        /// 设定URL中的键值
        /// </summary>
        /// <param name="strUrl">超级链接，至少包含?及后面部分</param>
        /// <param name="strKey">键</param>
        /// <param name="strValue">值</param>
        /// <example>SetUrlKeyValue("list?s=1", "s", "2") = "list?s=2"</example>
        /// <returns></returns>
        public static string SetUrlKeyValue(string strUrl, string strKey, string strValue)
        {
            if (string.IsNullOrEmpty(strUrl) || string.IsNullOrEmpty(strKey))
            {
                return strUrl;
            }
            if (strUrl.IndexOf('?') < 0)
            {
                strUrl = string.Format("{0}?{1}={2}", strUrl, strKey, strValue);
            }
            else
            {
                if (strUrl.IndexOf("?" + strKey + "=") >= 0 || strUrl.IndexOf("&" + strKey + "=") >= 0)
                {
                    strUrl = Regex.Replace(strUrl, "([?|&])(" + strKey + "=[^&]*)", "$1" + strKey + "=" + strValue, RegexOptions.Compiled | RegexOptions.IgnoreCase);
                }
                else
                {
                    strUrl = string.Format("{0}&{1}={2}", strUrl, strKey, strValue);
                }
            }
            return strUrl;
        }
        /// <summary>
        /// 删除URL中的键值
        /// </summary>
        /// <param name="strUrl">超级链接，至少包含?及后面部分</param>
        /// <param name="strKey">键</param>
        /// <example>RemoveUrlKeyValue("list?s=1", "s") = "list"</example>
        /// <returns></returns>
        public static string RemoveUrlKeyValue(string strUrl, string strKey)
        {
            if (string.IsNullOrEmpty(strUrl) || string.IsNullOrEmpty(strKey))
            {
                return strUrl;
            }
            if (strUrl.IndexOf("?" + strKey + "=") >= 0 || strUrl.IndexOf("&" + strKey + "=") >= 0)
            {
                strUrl = Regex.Replace(strUrl, "([?|&])(" + strKey + "=[^&]*)", "$1", RegexOptions.Compiled | RegexOptions.IgnoreCase);
            }
            return strUrl.TrimEnd('?', '&').Replace("?&", "?").Replace("&&", "&");
        }
        #endregion

        #region 获取/设置Route Url中变量
        /// <summary>
        /// 设置Url变量
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="strUrl"></param>
        /// <param name="strKey"></param>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static string SetUrlKeyValue(this HtmlHelper htmlHelper, string strKey, string strValue)
        {
            string url = null;
            HttpRequestBase request = htmlHelper.ViewContext.HttpContext.Request;
            RouteValueDictionary dictionary = new RouteValueDictionary(htmlHelper.ViewContext.RouteData.Values);
            string query = request.QueryString.Count > 0 ? string.Concat("?", request.QueryString) : "";
            if (dictionary.ContainsKey(strKey))
            {
                dictionary[strKey] = strValue;
                url = new UrlHelper(htmlHelper.ViewContext.RequestContext).RouteUrl(dictionary) + query;
            }
            else
            {
                url = SetUrlKeyValue(request.Url.AbsoluteUri, strKey, strValue);
            }
            return url;
        }

        /// <summary>
        /// 移除Url变量
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="strUrl"></param>
        /// <param name="strKey"></param>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static string RemoveUrlKeyValue(this HtmlHelper htmlHelper, string strKey)
        {
            string url = null;
            HttpRequestBase request = htmlHelper.ViewContext.HttpContext.Request;
            RouteValueDictionary dictionary = new RouteValueDictionary(htmlHelper.ViewContext.RouteData.Values);
            string query = request.QueryString.Count > 0 ? string.Concat("?", request.QueryString) : "";
            if (dictionary.ContainsKey(strKey))
            {
                dictionary.Remove(strKey);
                url = new UrlHelper(htmlHelper.ViewContext.RequestContext).RouteUrl(dictionary) + query;
            }
            else
            {
                url = RemoveUrlKeyValue(request.Url.AbsoluteUri, strKey);
            }
            return url;
        }

        /// <summary>
        /// 获取Url变量值
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public static string GetUrlKeyValue(this HtmlHelper htmlHelper, string strKey)
        {
            string value = null;
            HttpRequestBase request = htmlHelper.ViewContext.HttpContext.Request;
            if (htmlHelper.ViewContext.RouteData.Values.ContainsKey(strKey))
            {
                value = htmlHelper.ViewContext.RouteData.Values.First(u => u.Key == strKey).Value as string;
            }
            else
            {
                value = request.QueryString[strKey];
            }
            return value;
        }
        #endregion
    }
}
